<?php

namespace App\Http\Controllers\Api;

use App\Models\AppUsers;
use App\Models\Bind;
use App\Models\Config;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class BindUserController extends Controller
{
    public function bindUser(Request $request)
    {
        $code = $request->post('code', '');
        if ($code == null) {
            return $this->errors('-1', '推广码不能为空');
        }

        $token = $request->post('token', '');
        $uuid  = $request->post('uuid', '');
        $user  = AppUsers::where('api_token', $token)->where('uuid', $uuid)->first();

        $bindUser = AppUsers::whereCode($code)->first();

        if ($bindUser) {

            if (Bind::where('bind_user_id', $bindUser->id)->first()) {
                return $this->errors(-1, '该用户已被绑定');
            }

            if ($bindUser->code == $user->code) {
                return $this->errors(-1, '不能绑定自己');
            }
            $bind = new Bind([
                'user_id'      => $user->id,
                'bind_user_id' => $bindUser->id
            ]);
            $bind->save();
            $bindUser->expires = Carbon::parse($bindUser->expires)->addDay(1)->format('Y-m-d H:i:s');
            $bindUser->save();
            $user->expires = Carbon::parse($user->expires)->addDay(1)->format('Y-m-d H:i:s');
            $user->save();

            return $this->success(200, '绑定成功');
        }

        return $this->errors('-1', '推广码不存在');
    }

    public function config()
    {
        $config = Config::first();
        return $this->success('200', '成功', $config ? $config->toArray() : []);
    }
}
